import { filterAuth, getDicByKey } from '@/support/common';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Card, message, Table } from 'antd';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import RevokedCertificatesModel from './revokedCertificatesModel';

import { routerRedux } from 'dva/router';
import moment from 'moment';

const mapStateToProps = state => ({
  equipmentCertificate: state.equipmentCertificate,
  loading: state.loading.effects['equipmentCertificate/fetch'],
});

let page = '';

const ecuTypeOptions = [
  // 0 ivi,1 tbox,2 一体机
  {
    value: '0',
    label: 'ivi',
  },
  {
    value: '1',
    label: 'tbox',
  },
  {
    value: '2',
    label: '一体机',
  },
  {
    value: '5',
    label: 'HAD',
  }
];
const revokeOptions = [
  {
    value: '0',
    label: '未指明原因',
  },
  {
    value: '1',
    label: '密钥泄密',
  },
  {
    value: '2',
    label: 'CA 泄密',
  },
  {
    value: '3',
    label: '从属关系改变',
  },
  {
    value: '4',
    label: '证书被取代',
  },
  {
    value: '5',
    label: '操作终止',
  },
  {
    value: '6',
    label: '从 CRL 删除',
  },
];

const statusOptions = [
  // 1-已下发未反馈，2- 下发成功， 3-下发失败，4-撤销成功，5-撤销失败
  {
    value: '1',
    label: '已下发未反馈',
  },
  {
    value: '2',
    label: '下发成功',
  },
  {
    value: '3',
    label: '下发失败',
  },
  {
    value: '4',
    label: '撤销成功',
  },
  {
    value: '5',
    label: '撤销失败',
  },
];
class EquipmentCertificate extends PureComponent<any, any> {
  CollectionsPageRef = React.createRef<any>();
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.any,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;

    dispatch({
      type: 'equipmentCertificate/clear',
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    // dispatch({
    //   type: 'ipda2/initData',
    // });
  }
  handleTableChange = (pagination: any, filters: any) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const { current, pageSize } = pagination;
    this.setState({ pagination });
    const params = {
      page: current - 1,
      size: pageSize,
      ...formValues,
      ...filters,
    };
  };

  handleRevokedCertificates = record => {
    this.CollectionsPageRef.current.open(record);
  };
  FormReset = () => {
    const { dispatch } = this.props;
    // this.setState({ formValues: {} })
    // dispatch({
    //   type: 'equipmentCertificate/clear'
    // });

    dispatch({
      type: 'equipmentCertificate/fetch',
      payload: { ...this.state.formValues },
    });
    // this.searchFormRef?.current?.handleSubmit();
    return false;
  };
  handleFormReset = () => {
    const { dispatch } = this.props;
    this.setState({ formValues: {} });
    dispatch({
      type: 'equipmentCertificate/clear',
    });
    this.searchFormRef?.current?.resetFields();
    return false;
  };

  render() {
    const {
      equipmentCertificate: {
        data: { list, pagination },
      },
      loading,
      dispatch,
      location: { pathname = '/' },
    } = this.props;
    page = pagination;
    const { formValues, tbox } = this.state;
    const _this = this;

    const columns = [
      {
        title: '设备编号',
        dataIndex: 'ecuId',
      },
      {
        title: '证书状态',
        dataIndex: 'certStatus',
        render: (text: any, recode: any) => {
          console.log('recode', recode);

          if (text || text === 0) {
            return statusOptions.find(i => i.value == text)?.label;
          } else {
            return text;
          }
        },
      },
      {
        title: '生产计划入库时间',
        dataIndex: 'planDate',
        render: (i: any) => {
          return moment(i).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 200,
        fixed: 'right',
        render: (text: any, record: any) => {
          console.log(record.certStatus, '21233');

          const delBtn = {
            title: '撤销证书',
            key: 'edit',
            disabled: !(
              record.certStatus === 1 ||
              record.certStatus === 2 ||
              record.certStatus === 5
            ),
            auth: 'revokedCertificates',
            Popconfirm: true,
            message: '证书撤销以后，零部件将无法进行安全的网络通信，您确认要撤销证书吗？',
            onConfirm: _this.handleRevokedCertificates.bind(this, record),
          };
          const btns = [];
          btns.push(delBtn);
          return <PateoAuthButtons btns={btns} max={1} pathname={pathname} />;
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };

    const searchItems = [
      {
        type: 'input',
        title: '设备编号',
        key: 'ecuId',
        // rules: [{ required: true, message: '请填写设备编号' }],
      },
      {
        type: 'select',
        title: '设备类型',
        key: 'ecuType',
        selectOptions: ecuTypeOptions,
        // rules: [{ required: true, message: '请选择设备类型' }],
      },
    ];

    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={ref => (this.searchFormRef = ref)}
            searchItems={searchItems}
            fetchParams={{ type: 'equipmentCertificate/fetch' }}
            saveFormValues={(val: any) =>
              this.setState({ formValues: Object.assign(formValues, val) })
            }
            handleFormReset={_this.handleFormReset.bind(_this)}
          />
        </Card>

        <Card style={{ marginTop: 12 }} bordered={false}>
          <Table
            size={'small'}
            rowKey={record => record.sid}
            dataSource={list}
            loading={loading}
            columns={columns}
            pagination={false}
            onChange={this.handleTableChange}
          />
        </Card>
        <RevokedCertificatesModel
          ref={this.CollectionsPageRef}
          dispatch={this.props.dispatch}
          options={revokeOptions}
          handleFormReset={this.FormReset.bind(this)}
          // resetOutterForm={this.handleFormReset}
        ></RevokedCertificatesModel>
      </div>
    );
  }
}
export default connect(mapStateToProps)(EquipmentCertificate);
